import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
import { Logger } from '@nestjs/common';
import * as ip from 'ip';
import * as chalk from 'chalk';
import { getSwaggerConfig, getSwaggerOptions } from './config/swagger.config';
import { getAppConfig } from './config/app.config';
import { ValidationPipe, BadRequestException } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true, // 自动转换类型
      whitelist: true, // 过滤掉未定义的属性
      forbidNonWhitelisted: true, // 禁止未定义的属性
      disableErrorMessages: false, // 启用错误消息
      transformOptions: { enableImplicitConversion: true },
      exceptionFactory: (errors) => {
        // 自定义错误响应格式
        const errorMessages = errors.map((error:any) => {

          return Object.values(error.constraints).join(', ');
        });
        return new BadRequestException({
          code: 400,
          message: errorMessages,
          error: 'Bad Request',
        });
      },
    }),
  );
  const env = process.env.NODE_ENV || 'development';
  const configService = app.get(ConfigService);
  const logger = new Logger('Bootstrap');

  // 启动应用
  const port = configService.get<number>('app.port') || 3000;
  const host = configService.get<string>('app.host') || 'localhost';
  // 输出访问地址
  const localIp = ip.address();

  // Swagger 配置
  const { globalPrefix } = getAppConfig(configService);
  app.setGlobalPrefix(globalPrefix);  // 如果使用全局前缀，Swagger路径需要相应调整
  // Swagger 配置
  const document = SwaggerModule.createDocument(app, getSwaggerConfig(env, localIp, port));
  // 添加全局响应
  document.paths = Object.keys(document.paths).reduce((acc, path) => {
    acc[path] = Object.keys(document.paths[path]).reduce((methods, method) => {
      methods[method] = {
        ...document.paths[path][method],
        responses: {
          ...document.paths[path][method].responses,
          200: { description: '请求成功' },
          400: { description: '请求参数无效' },
          401: { description: '未授权' },
          403: { description: '禁止访问' },
          404: { description: '资源未找到' },
          500: { description: '服务器内部错误' },
        },
      };
      return methods;
    }, {});
    return acc;
  }, {});

  SwaggerModule.setup('api-docs', app, document, getSwaggerOptions(env));



  await app.listen(process.env.PORT ?? 3000);

  logger.log(
    `${chalk.green('🚀')} Application is running on: ${chalk.blue(`http://${host}:${port}`)}`,
  );
  logger.log(
    `${chalk.green('📚')} Swagger UI is available at: ${chalk.blue(`http://${host}:${port}/api-docs`)}`,
  );
  logger.log(
    `${chalk.green('🌐')} Local IP access: ${chalk.blue(`http://${localIp}:${port}`)}`,
  );
  logger.log(
    `${chalk.green('📖')} Local Swagger UI: ${chalk.blue(`http://${localIp}:${port}/api-docs`)}`,
  );
}
bootstrap();
